<?php
namespace app\controllers;


use app\logic\AreaLogic;
use app\logic\MoneyLogic;
use app\logic\ShopLogic;
use yii;

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('PRC');


/** 引入PHPExcel */
/*require_once dirname(__FILE__) . '/../common/corelib/plugins/phpExcel/PHPExcel.php';
use app\common\corelib\plugins\phpExcel\PHPExcel;*/

class CommissionController extends BackendController
{

    public function actionConfig()
    {
        $moneyLogic = new MoneyLogic();
        if(!Yii::$app->request->post()) {
            $commission = $moneyLogic->getDefaultConfig();
            $plan = $moneyLogic->getPlan();
            foreach ($commission AS $k => $v) {
                $config_ext = json_decode($v['config_ext'], true);
                $commission[$k]['role'] = $config_ext['role'];
                $commission[$k]['type'] = $config_ext['type'];
            }
            $this->data['breadcrumbs'] = '佣金配置';
            return $this->render('config', [
                'commission' => $commission,
                'plan' => $plan
            ]);
        }else{
            $plan_id = Yii::$app->request->post('plan_id');
            $commission = $moneyLogic->getConfig($plan_id);
            foreach ($commission AS $k => $v) {
                $config_ext = json_decode($v['config_ext'], true);
                $commission[$k]['role'] = $config_ext['role'];
                $commission[$k]['type'] = $config_ext['type'];
            }
            echo json_encode($commission);
        }
    }

    public function actionAdd(){
        $moneyLogic = new MoneyLogic();
        if(!Yii::$app->request->post()){
            $commission = $moneyLogic->getDefaultConfig();
            foreach($commission AS $k=>$v){
                $config_ext = json_decode($v['config_ext'],true);
                $commission[$k]['role'] = $config_ext['role'];
                $commission[$k]['type'] = $config_ext['type'];
            }
            $this->data['breadcrumbs'] = '添加佣金配置';
            $plan_id = $moneyLogic->getMaxPlan();
            $plan_id = $plan_id['plan_id']+1;
            return $this->render('add', [
                'theme' => '/assets/',
                'commission' => $commission,
                'plan_id'=>$plan_id
            ]);
        }else{
            $logicRes = true;
            $params = Yii::$app->request->post('value');
            $id = Yii::$app->request->post('plan_id');
            foreach ($params AS $key=>&$value){
                if(!$value)
                    $value = 0;
                $logicRes &= $moneyLogic->addConfig($key,$value,$id);
            }
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','新增佣金配置成功');
                jump('commission/config');
            } else {
                Yii::$app->getSession()->setFlash('error','新增佣金配置失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }
    }

    public function actionEdit()
    {
        $moneyLogic = new MoneyLogic();
        if(!Yii::$app->request->post()){
            $id = Yii::$app->request->get('config_id');
            $config = $moneyLogic->getConfigById($id);
            $config_ext = json_decode($config['config_ext'],true);
            $config['role'] = $config_ext['role'];
            $config['type'] = $config_ext['type'];
            $this->data['breadcrumbs'] = ['佣金配置管理' => U('commission/config'), '更新' => ''];
            return $this->render('edit', [
                'config' => $config,
                'actionUrl' => U('commission/edit'),
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $id = Yii::$app->request->post('config_id');
            $logicRes = $moneyLogic->editConfigById($id,$params);
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','更新佣金配置成功');
                jump('commission/config');
            } else {
                Yii::$app->getSession()->setFlash('error','更新佣金配置失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }
    }

    public function actionIndex()
    {
        $moneyLogic = new MoneyLogic();

        if(!Yii::$app->request->post()){
            $start_time = date('Y-m-01 00:00:00', time());
            $start_time_temp = date('Y-m-01', time());
            $end_time = date('Y-m-d 23:59:59', strtotime("$start_time_temp +1 month -1 day"));
            $commission = [];
            $commission0 = $moneyLogic->getCommission($start_time,$end_time,0,[]);
            foreach($commission0 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['quan'] = $value['income'];
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission1= $moneyLogic->getCommission($start_time,$end_time,1,[]);
            foreach($commission1 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['card'] = $value['income'];
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission2= $moneyLogic->getCommission($start_time,$end_time,2,[]);
            foreach($commission2 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['sale_goods'] = $value['income'];
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission3= $moneyLogic->getCommission($start_time,$end_time,3,[]);
            foreach($commission3 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['recovery_goods'] = $value['income'];
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }

            $commission4= $moneyLogic->getCommission($start_time,$end_time,4,[]);
            foreach($commission4 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['yoyo'] = $value['income'];
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission = array_values($commission);
            foreach($commission AS $k=>&$v){
                $v['quan'] = isset($v['quan'])?$v['quan']:0;
                $v['card'] = isset($v['card'])?$v['card']:0;
                $v['sale_goods'] = isset($v['sale_goods'])?$v['sale_goods']:0;
                $v['recovery_goods'] = isset($v['recovery_goods'])?$v['recovery_goods']:0;
                $v['yoyo'] = isset($v['yoyo'])?$v['yoyo']:0;
                $v['total'] = $v['quan']+$v['card']+$v['sale_goods']+$v['recovery_goods']+$v['yoyo'];
            }
            //var_dump($commission);exit;
            $shopLogic = new ShopLogic();
            $shop = $shopLogic->getAllShops();
            $areaLogic = new AreaLogic();
            $province = $areaLogic->getProvince();
            $this->data['breadcrumbs'] = '佣金对账列表';
            return $this->render('index', [
                'theme' => '/assets/',
                'commission' => $commission,
                'shop'=>$shop,
                'province'=>$province
            ]);
        }else{

            $params = Yii::$app->request->post('form');
            $start_time = $params['start_time'];
            $start_time = $start_time . "-01 00:00:00";
            $start_time_temp = date('Y-m-01', strtotime($start_time));
            $end_time = date('Y-m-d 23:59:59', strtotime("$start_time_temp +1 month -1 day"));
            $commission = [];
            $commission0 = $moneyLogic->getCommission($start_time,$end_time,0,$params);
            foreach($commission0 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['quan'] = isset($value['income'])?$value['income']:0;
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission1= $moneyLogic->getCommission($start_time,$end_time,1,$params);
            foreach($commission1 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['card'] = isset($value['income'])?$value['income']:0;
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission2= $moneyLogic->getCommission($start_time,$end_time,2,$params);
            foreach($commission2 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['sale_goods'] = isset($value['income'])?$value['income']:0;
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission3= $moneyLogic->getCommission($start_time,$end_time,3,$params);
            foreach($commission3 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['recovery_goods'] = isset($value['income'])?$value['income']:0;
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }

            $commission4= $moneyLogic->getCommission($start_time,$end_time,4,$params);
            foreach($commission4 AS $key=>$value){
                $commission[$value['shop_id'].','.$value['user_id']]['shop_name'] = $value['shop_name'];
                $commission[$value['shop_id'].','.$value['user_id']]['phone'] = $value['phone'];
                $commission[$value['shop_id'].','.$value['user_id']]['type'] = $value['type'];
                $commission[$value['shop_id'].','.$value['user_id']]['yoyo'] = isset($value['income'])?$value['income']:0;
                $commission[$value['shop_id'].','.$value['user_id']]['province'] = $value['province'];
                $commission[$value['shop_id'].','.$value['user_id']]['city'] = $value['city'];
                $commission[$value['shop_id'].','.$value['user_id']]['district'] = $value['district'];
                $commission[$value['shop_id'].','.$value['user_id']]['street'] = $value['street'];
            }
            $commission = array_values($commission);
            foreach($commission AS $k=>&$v){
                $v['quan'] = isset($v['quan'])?$v['quan']:0;
                $v['card'] = isset($v['card'])?$v['card']:0;
                $v['sale_goods'] = isset($v['sale_goods'])?$v['sale_goods']:0;
                $v['recovery_goods'] = isset($v['recovery_goods'])?$v['recovery_goods']:0;
                $v['yoyo'] = isset($v['yoyo'])?$v['yoyo']:0;
                $v['total'] = $v['quan']+$v['card']+$v['sale_goods']+$v['recovery_goods']+$v['yoyo'];
            }
            //echo json_encode($commission);
            $areaLogic = new AreaLogic();
            $province = $areaLogic->getProvinces($params['province_id']);
            $selprovince = $areaLogic->getSelProvince($params['province_id']);
            $city = $areaLogic->getCitys($params['province_id'],$params['city_id']);
            $selcity = $areaLogic->getSelCity($params['city_id']);
            $district = $areaLogic->getDistricts($params['city_id'],$params['district_id']);
            $seldistrict = $areaLogic->getSelDistrict($params['district_id']);
            $street = $areaLogic->getStreets($params['district_id'],$params['street_id']);
            $selstreet = $areaLogic->getSelStreet($params['street_id']);
            $shopLogic = new ShopLogic();
            $shop = $shopLogic->getAllShops();
            $selshop = $shopLogic->getById($params['shop_id']);
            if(Yii::$app->request->post('submit')=="搜索"){
                return $this->render('index', [
                    'theme' => '/assets/',
                    'commission' => $commission,
                    'start_time'=>$params['start_time'],
                    'shop'=>$shop,
                    'selshop'=>$selshop,
                    'province'=>$province,
                    'selprovince'=>$selprovince,
                    'city'=>$city,
                    'selcity'=>$selcity,
                    'district'=>$district,
                    'seldistrict'=>$seldistrict,
                    'street'=>$street,
                    'selstreet'=>$selstreet,
                ]);
            }else{

                // 创建Excel文件对象
                $objPHPExcel = new \PHPExcel();
// 设置文档信息，这个文档信息windows系统可以右键文件属性查看
                $objPHPExcel->getProperties()->setCreator("儿嬉科技")
                    ->setTitle("佣金对账列表");


//根据excel坐标，添加数据
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', '序号')
                    ->setCellValue('B1', '区域')
                    ->setCellValue('C1', '商家名称')
                    ->setCellValue('D1', '账号')
                    ->setCellValue('E1', '角色')
                    ->setCellValue('F1', '入场券订单分佣')
                    ->setCellValue('G1', '会员卡订单分佣')
                    ->setCellValue('H1', '商品订单出售分佣')
                    ->setCellValue('I1', '商品订单回收分佣')
                    ->setCellValue('J1', '摇摇车分佣')
                    ->setCellValue('K1', '分佣总和');

                foreach($commission AS $ke=>$va){
                    $role = $va['type']==1?"店主":"店长";
                    $keys = $ke+2;
                    $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A'.$keys, $ke+1)
                        ->setCellValue('B'.$keys, $va['province'].$va['city'].$va['district'].$va['street'])
                        ->setCellValue('C'.$keys, $va['shop_name'])
                        ->setCellValue('D'.$keys, $va['phone'])
                        ->setCellValue('E'.$keys, $role)
                        ->setCellValue('F'.$keys, $va['quan'])
                        ->setCellValue('G'.$keys, $va['card'])
                        ->setCellValue('H'.$keys, $va['sale_goods'])
                        ->setCellValue('I'.$keys, $va['recovery_goods'])
                        ->setCellValue('J'.$keys, $va['yoyo'])
                        ->setCellValue('K'.$keys, $va['total']);
                }

// 设置第一个sheet为工作的sheet
                $objPHPExcel->setActiveSheetIndex(0);

                $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                header('pragma:public');
                header("Content-Disposition:attachment;filename=佣金对账列表".date('_YmdHis').".xlsx");
                $objWriter->save('php://output');exit;

// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx



            }

        }

    }






}